package com.aflac.proxy.jdk;

import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
// Java Proxy
// 1. 首先实现一个InvocationHandler，方法调用会被转发到该类的invoke()方法。

class LogInvocationHandler implements InvocationHandler {

	private Hello hello;

	public LogInvocationHandler(Hello hello) {
		this.hello = hello;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if ("sayHello".equals(method.getName())) {
			System.out.println("You said: " + Arrays.toString(args));
		}
		return method.invoke(hello, args);
	}

	public static void main(String[] args) {
		String name="sun.misc.ProxyGenerator.saveGeneratedFiles";
		int i = name.lastIndexOf('.');
		String temp=name.substring(0, i).replace('.', File.pathSeparatorChar);
		System.out.println(temp);
		
		System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
		Hello hello = (Hello) Proxy.newProxyInstance(LogInvocationHandler.class.getClassLoader(), // 1. 类加载器
				new Class<?>[] { Hello.class }, // 2. 代理需要实现的接口，可以有多个
				new LogInvocationHandler(new HelloImp()));// 3. 方法调用的实际处理者
		System.out.println(hello.sayHello("I love you!"));
		/*int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
		System.out.println(accessFlags);
		String proxyPkg = null;     // package to define proxy class in
		  
		for (Class<?> intf : new Class<?>[] { Hello.class }) {
              int flags = intf.getModifiers();
              if (!Modifier.isPublic(flags)) {
                  accessFlags = Modifier.FINAL;
                 
                  String name = intf.getName();
                  int n = name.lastIndexOf('.');
                  String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                  if (proxyPkg == null) {
                      proxyPkg = pkg;
                      System.out.println(pkg);
                  } else if (!pkg.equals(proxyPkg)) {
                      throw new IllegalArgumentException(
                          "non-public interfaces from different packages");
                  }
              }
          }*/
	}
}